﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cua_Hang.DTO;
using System.IO;
using System.Data;
using System.Text.RegularExpressions;

namespace Cua_Hang.Admin
{
    public partial class QuanLy_ChiTiet_SanPham : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Login"] != null)
            {
                if (!IsPostBack)
                {
                    this.HienTenSPVao_Dropdownlist();
                }
                this.HienSPTheoID_cuahang_vaoGirV();
                Bt_CapNhat.Visible = false;
            }
            else
            {
                Response.Redirect("http://localhost:1482/DangNhap.aspx");
            }
        }
        //=========================================================
        //--hien ten san pham vao dropdownlist
        void HienTenSPVao_Dropdownlist()
        {
            Cua_Hang.DTO.ChiTiet_CuaHang_DTO chang = new DTO.ChiTiet_CuaHang_DTO();
            DDL_TenSanPham.DataSource = Cua_Hang.BUS.ChiTiet_CuaHang_BUS.ListChiTiet_CuaHangAll_BUS(Convert.ToInt32(Session["Login"].ToString()));//cho nay chua lam dang nhap
            DDL_TenSanPham.DataTextField = "Ten_ChiTiet_CuaHang";
            DDL_TenSanPham.DataValueField = "ID_ChiTiet_CuaHang";
            
            //DDL_TenSanPham.DataValueField = "ID_cuahang";
            DDL_TenSanPham.DataBind();
            
            //chang.ID_cuahang = int.Parse(Tbxoa_idcuahang.Text);
            //Cua_Hang.BUS.Cua_Hang_BUS.XoaCuaHang_BUS(chang);
        }
        //==========================================================
        //--load Chi Tiet San Pham theo id cua hang
        void HienSPTheoID_cuahang_vaoGirV()
        {
            //cho nay chua lam dang nhap
            int ma = Convert.ToInt32(Session["Login"].ToString());//cho nay chua lam dang nhap
            GV_ChiTietSanPham.DataSource = Cua_Hang.BUS.ChiTiet_SanPham_BUS.List_ChiTiet_SanPham_Theo_id_cuahang_BUS(ma);//cho nay nho dang nhap
            GV_ChiTietSanPham.DataBind();
        }
        
        //============= chuyen List thanh DataTable===========================
        //
        public DataTable ConvertListChiTietSP_DTOToDataTable(List<ChiTiet_SanPham_DTO> lst)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("ID_ChiTiet_SanPham");
            dt.Columns.Add("Ten_ChiTiet_SanPham");
            dt.Columns.Add("ID_ChiTiet_CuaHang");
            dt.Columns.Add("Anh_ChiTiet_SanPham");
            dt.Columns.Add("Gia_ChiTiet_SanPham");
            dt.Columns.Add("ThongTin_ChiTiet_SanPham");
            dt.Columns.Add("GhiChu_ChiTiet_SanPham");
            for (int i = 0; i < lst.Count; i++)
            {
                dt.Rows.Add(
                        lst[i].ID_ChiTiet_SanPham,
                        lst[i].Ten_ChiTiet_SanPham,
                        lst[i].ID_ChiTiet_CuaHang,
                        lst[i].Anh_ChiTiet_SanPham,
                        lst[i].Gia_ChiTiet_SanPham,
                        lst[i].ThongTin_ChiTiet_SanPham,
                        lst[i].GhiChu_ChiTiet_SanPham


                    );
            }
            return dt;
        }

        //============= ket thuc chuyen List thanh DataTable=======================
        //==============ham hien vao textbox ten chi tiet sp theo id =================
        public ChiTiet_SanPham_DTO ShowChiTietSP_TheoID(int ID_ChiTiet_SanPham)
        {
            ChiTiet_SanPham_DTO dm = new ChiTiet_SanPham_DTO();
            List<ChiTiet_SanPham_DTO> lst = BUS.ChiTiet_SanPham_BUS.List_ChiTiet_TheoId_SanPham_BUS(ID_ChiTiet_SanPham);
            DataTable dt = new DataTable();
            dt = ConvertListChiTietSP_DTOToDataTable(lst);
            foreach (DataRow dr in dt.Rows)
            {
                //dm.ID_cuahang = (int)dr["ID_cuahang"];
                //dm.ID_cuahang = (int)dr["ID_cuahang"];
                dm.Ten_ChiTiet_SanPham = dr["Ten_ChiTiet_SanPham"].ToString();
                //dm.ID_ChiTiet_CuaHang = (int)dr["ID_ChiTiet_CuaHang"];
                dm.Anh_ChiTiet_SanPham = dr["Anh_ChiTiet_SanPham"].ToString();
                dm.Gia_ChiTiet_SanPham =Convert.ToDouble(dr["Gia_ChiTiet_SanPham"]);
                dm.ThongTin_ChiTiet_SanPham = dr["ThongTin_ChiTiet_SanPham"].ToString();
                dm.GhiChu_ChiTiet_SanPham = dr["GhiChu_ChiTiet_SanPham"].ToString();



            }
            return dm;
        }
        //======================================================================
        //----ham cap nhat chi tiet sp
        private void CapNhatChiTietsp()
        {
            ChiTiet_SanPham_DTO dm = new ChiTiet_SanPham_DTO();
            //LayThongTinChiTietCuaHang(ref dm);
            dm.ID_ChiTiet_CuaHang = Convert.ToInt32(DDL_TenSanPham.SelectedValue);
            dm.ID_ChiTiet_SanPham =Convert.ToInt32( Id_chitietsp.Text);
            dm.Ten_ChiTiet_SanPham = TB_TenChiTietSanPham.Text;
            dm.Gia_ChiTiet_SanPham =Convert.ToDouble( TB_GiaSanPham.Text);
            dm.ThongTin_ChiTiet_SanPham = TBThongTinChiTietSP.Text;
            dm.GhiChu_ChiTiet_SanPham = TBGhiChuChiTietSP.Text;
            Cua_Hang.BUS.ChiTiet_SanPham_BUS.SuaChiTietSP_BUS(dm);

        }
        protected void Bt_CapNhat_Click(object sender, EventArgs e)
        {
            if(KiemTra()==true)
            {
                this.CapNhatChiTietsp();
                this.HienSPTheoID_cuahang_vaoGirV();
                this.Bt_Them.Visible = true;
                TB_GiaSanPham.Text = "";
                TBGhiChuChiTietSP.Text = "";
                TB_TenChiTietSanPham.Text = "";
                TBThongTinChiTietSP.Text = "";
            }
        }
        //==========================================================
        protected void GV_ChiTietSanPham_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            Int32 index = Int32.Parse(e.CommandArgument.ToString());
            if (e.CommandName == "Xoa")
            {
                //String Code = GV_ChiTietSanPham.DataKeys[index].Value.ToString();
                Cua_Hang.DTO.ChiTiet_SanPham_DTO chang = new DTO.ChiTiet_SanPham_DTO();
                chang.ID_ChiTiet_SanPham = Convert.ToInt32(e.CommandArgument);
                //--xoa anh trong thu muc
                ChiTiet_SanPham_DTO dmn = new ChiTiet_SanPham_DTO();
                dmn = ShowChiTietSP_TheoID((Convert.ToInt32(e.CommandArgument)));
                string TenAnh=dmn.Anh_ChiTiet_SanPham.ToString();
                this.replaceImg(TenAnh);
                //
                Cua_Hang.BUS.ChiTiet_SanPham_BUS.XoaChiTietSP_BUS(chang);
                this.HienSPTheoID_cuahang_vaoGirV();
            }
        }
        //==========================================================
        protected void GV_ChiTietSanPham_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            
        }
        //==========================================================
        protected void GV_ChiTietSanPham_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GV_ChiTietSanPham.PageIndex = e.NewPageIndex;
            this.HienSPTheoID_cuahang_vaoGirV();
        }
        //==========================================================
        protected string UploadImage(FileUpload file)
        {

            if (file.FileName.Trim() == null)
            {
                return "default.gif";
            }
            string fileName = file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1);
            if (file.HasFile)
            {
                string filePath = MapPath("~/images/" + fileName);
                file.SaveAs(filePath);
            }


            return fileName;
        }
        //--------------------------------------------------------------
        private Boolean replaceImg( string Tenhinh)
        {
            //Tenhinh = "sp7.jpg";
            //string imgName = "ca.jpg";
            //string subName = imgName.Remove(0,9);//chổ này là do cái thư mục dẫn vào cũa mình là ~/Images/ nên mình cát bỏ 9 kí tự đầu đễ lấy dc cái filename
            DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/images/"));
            foreach (FileInfo f in dir.GetFiles(Tenhinh))
            {
                if (f.Exists)
                {
                    f.Delete();
                    return true;
                }
            }
            return false;
        }
        //----------them chi tiet san pham------------------------------
        void ThemChiTietSP_GUI()
        {
            ChiTiet_SanPham_DTO ct = new ChiTiet_SanPham_DTO();

            ct.Ten_ChiTiet_SanPham = TB_TenChiTietSanPham.Text;
            ct.ID_ChiTiet_CuaHang = Convert.ToInt32(DDL_TenSanPham.SelectedValue);
            ct.Anh_ChiTiet_SanPham = UploadImage(uplImage);
            ct.Gia_ChiTiet_SanPham =float.Parse(TB_GiaSanPham.Text);
            ct.ThongTin_ChiTiet_SanPham = TBThongTinChiTietSP.Text;
            ct.GhiChu_ChiTiet_SanPham = TBGhiChuChiTietSP.Text;
            Cua_Hang.BUS.ChiTiet_SanPham_BUS.ThemChiTietSP_BUS(ct);
        }
        protected void Bt_Them_Click(object sender, EventArgs e)
        {
            if (KiemTra() == true)
            {
                Cua_Hang.DTO.ChiTiet_SanPham_DTO chang = new DTO.ChiTiet_SanPham_DTO();
                chang.Ten_ChiTiet_SanPham = TB_TenChiTietSanPham.Text;
            
                if (Cua_Hang.BUS.ChiTiet_SanPham_BUS.KiemTraTrung_ChiTiet_SP_BUS(chang) == false)
                {
                    this.ThemChiTietSP_GUI();
                    this.HienSPTheoID_cuahang_vaoGirV();
                    TB_GiaSanPham.Text = "";
                    TBGhiChuChiTietSP.Text = "";
                    TB_TenChiTietSanPham.Text = "";
                    TBThongTinChiTietSP.Text = "";
                }
                else
                {
                    Response.Write(@"<script language = 'javascript'>alert ('Tên sản phẩm đã tồn tại !'); </script>");
                }
            }

            //TB_Id_chitietcuahang.Text = DDL_TenSanPham.SelectedItem.Text;
        }

        protected void GV_ChiTietSanPham_SelectedIndexChanged(object sender, EventArgs e)
        {
            int ID_ChiTiet_SanPham = Convert.ToInt32(GV_ChiTietSanPham.SelectedRow.Cells[0].Text);
            ChiTiet_SanPham_DTO dmn = new ChiTiet_SanPham_DTO();
            dmn = ShowChiTietSP_TheoID(ID_ChiTiet_SanPham);
            TB_TenChiTietSanPham.Text = dmn.Ten_ChiTiet_SanPham.ToString();
            TBThongTinChiTietSP.Text = dmn.ThongTin_ChiTiet_SanPham.ToString();
            TBGhiChuChiTietSP.Text = dmn.GhiChu_ChiTiet_SanPham.ToString();
            TB_GiaSanPham.Text = dmn.Gia_ChiTiet_SanPham.ToString();
            Id_chitietsp.Text = ID_ChiTiet_SanPham.ToString();
            //Tb_TenSanPham.Text = dmn.Ten_ChiTiet_CuaHang.ToString();
            //Id_tensanpham.Text = ID_ChiTiet_CuaHang.ToString();
            //this.Bt_themsanpham.Visible = false;
            // this.Bt_capnhatsanpham.Visible = true;
            this.Bt_CapNhat.Visible = true;
            this.Bt_Them.Visible = false;
        }
        //==========================================================
        private bool CheckNumber(string str)
        {
            //ham kiem tra so nguyen
                //foreach (Char c in pValue)
                //{
                //    if (!Char.IsDigit(c))
                //        return false;
                //}
                //return true;
            //
            //Convert.ToInt32(str);
            //return true;
            try
            {
                    ////Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
                    //Convert.ToDouble(str);
                    //return true;
                Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
                return regex.IsMatch(str);
                 
            }
            catch
            {
                return false;
            }

        }
        private bool KiemTra()
        {
            if (this.TB_TenChiTietSanPham.Text.Trim() == "")
            {
                Response.Write(@"<script language = 'javascript'>alert ('Bạn chưa nhập tên sản phẩm!'); </script>");

                return false;
            }
            if (this.TBThongTinChiTietSP.Text.Trim() == "")
            {
                Response.Write(@"<script language = 'javascript'>alert ('Bạn chưa nhập thông tin về sản phẩm!'); </script>");

                return false;
            }
           //--gia
            
            if (this.TB_GiaSanPham.Text.Trim() == "")
            {
                Response.Write(@"<script language = 'javascript'>alert ('Bạn chưa nhập giá sản phẩm'); </script>");

                return false;
            }
            if (CheckNumber(this.TB_GiaSanPham.Text) == false)
            {
                Response.Write(@"<script language = 'javascript'>alert ('Giá nhập phải là giá trị số (viết liền không có dấu phải)!'); </script>");
                TB_GiaSanPham.Focus();
                return false;
            }
            if (Convert.ToDouble(this.TB_GiaSanPham.Text) <= 0)
            {
                Response.Write(@"<script language = 'javascript'>alert ('Giá nhập phải là giá trị > 0!'); </script>");
                TB_GiaSanPham.Focus();
                return false;
            }



            return true;


        }

    }
}